import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.tree.TreeNode;


public class RootNode implements TreeNode
{
	private Map<String,AgentNode> m_agents;
	private String m_text;
	
	public RootNode(String text)
	{
		m_text = text;
		m_agents= new HashMap<String,AgentNode>();
	}
	
	public String getText()
	{
		return m_text;
	}
	
	public void setText(String text)
	{
		m_text = text;
	}
	
	public List<AgentNode> getAgents()
	{
		return Collections.list(Collections.enumeration(m_agents.values()));
	}
	
	// null means new agent, otherwise old
	public AgentNode addAgent(AgentNode agent)
	{
		// If the agent already exists, set isAlive to true
		AgentNode oldAgent = m_agents.get(agent.getHost());
		if(oldAgent != null)
		{
			oldAgent.setIsAlive(true);
			return oldAgent;
		}
		else
		{
			m_agents.put(agent.getHost(),agent);
			return null;
		}
	}
	
	public String toString()
	{
		return m_text;
	}
	
	@Override
	public boolean equals(Object obj)
	{
		if(obj == null)
			return false;
		
		if (!(obj instanceof AgentNode))
			return false;
		
		RootNode other = (RootNode)obj;
		return getText().equals(other.getText());
	}
	
	public int hashCode()
	{
		return getText().hashCode();
	}

	@Override
	public TreeNode getChildAt(int childIndex) 
	{
		return m_agents.get(childIndex);
	}

	@Override
	public int getChildCount() 
	{
		return m_agents.size();
	}

	@Override
	public TreeNode getParent() 
	{
		return null;
	}

	@Override
	public int getIndex(TreeNode node) 
	{
		return Collections.list(Collections.enumeration(m_agents.values())).indexOf(node);
	}

	@Override
	public boolean getAllowsChildren() 
	{
		return true;
	}

	@Override
	public boolean isLeaf() 
	{
		return false;
	}

	@Override
	public Enumeration children() 
	{
		return Collections.enumeration(m_agents.values());
	}
}
